package cvi.com.reader.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import cvi.com.reader.R;
import cvi.com.reader.base.BaseActivity;
import cvi.com.reader.bean.ForgotPassWordBean;
import cvi.com.reader.bean.LoginBean;
import cvi.com.reader.bean.RegisterQuestionBean;
import cvi.com.reader.bean.constant;
import cvi.com.reader.network.DefaultObserver;
import cvi.com.reader.network.NetWorkManager;
import cvi.com.reader.tool.UtilsOnclickListen;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

import static cvi.com.reader.bean.constant.CLOSElOGIN_MYRECEIVER;

/**
 * Created by 梅涛 on 2020/11/17.
 */

public class ForgotPassWordActivity extends BaseActivity implements View.OnClickListener {
    @BindView(R.id.back)
    LinearLayout back;
    @BindView(R.id.tittle)
    TextView tittle;
    @BindView(R.id.right_icon)
    LinearLayout rightIcon;
    @BindView(R.id.account)
    EditText account;
    @BindView(R.id.secret_insurance_spinner)
    Spinner secretInsuranceSpinner;
    @BindView(R.id.secret_insurance_answer)
    EditText secretInsuranceAnswer;
    @BindView(R.id.verify)
    TextView verify;
    @BindView(R.id.success)
    ImageView success;
    @BindView(R.id.password)
    EditText password;
    @BindView(R.id.pwd_check_box)
    CheckBox pwdCheckBox;
    @BindView(R.id.re_password)
    EditText rePassword;
    @BindView(R.id.re_pwd_check_box)
    CheckBox rePwdCheckBox;
    @BindView(R.id.scrollView)
    ScrollView scrollView;
    @BindView(R.id.reset)
    Button reset;
    @BindView(R.id.aa)
    TextView aa;
    @BindView(R.id.bb)
    TextView bb;
    private int questionId;
    //是否验证成功
    private boolean isVerify = false;
    private String token;
    private int uid;

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.reset:
                if (UtilsOnclickListen.isFastClick()) {
                    if (!password.getText().toString().trim().equals(rePassword.getText().toString().trim())) {
                        Toast.makeText(ForgotPassWordActivity.this, "两次输入的密码不一致！", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (password.getText().toString().trim().isEmpty()) {
                        Toast.makeText(ForgotPassWordActivity.this, "密码不能为空！", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (password.getText().toString().trim().length() < 6) {
                        Toast.makeText(ForgotPassWordActivity.this, "密码长度至少是六位！", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    if (token.isEmpty()) {
                        Toast.makeText(ForgotPassWordActivity.this, "请先验证密保问题！", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    resetPassWord();
                }
                break;
            case R.id.verify:
                if (UtilsOnclickListen.isFastClick()) {
                    if (account.getText().toString().trim().length() < 6) {
                        Toast.makeText(ForgotPassWordActivity.this, "账户长度至少是六位！", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (secretInsuranceAnswer.getText().toString().trim().isEmpty()) {
                        Toast.makeText(ForgotPassWordActivity.this, "密保问题不能为空！", Toast.LENGTH_SHORT).show();
                        return;

                    }
                    verification();
                }
                break;
        }

    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_forgot_password;
    }

    @Override
    protected void initView() {
        tittle.setText("忘记密码");
        back.setOnClickListener(this);
        reset.setOnClickListener(this);
        verify.setOnClickListener(this);
        rePwdCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    rePassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());//选中CheckBox，显示密码
                } else {
                    rePassword.setTransformationMethod(PasswordTransformationMethod.getInstance());//隐藏密码
                }

            }
        });
        pwdCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    password.setTransformationMethod(HideReturnsTransformationMethod.getInstance());//选中CheckBox，显示密码
                } else {
                    password.setTransformationMethod(PasswordTransformationMethod.getInstance());//隐藏密码
                }

            }
        });

    }

    @Override
    protected void initData() {
        //密保问题接口
        NetWorkManager.getInstance().getNetWorkApiService().getRegisterQuestion().compose(this.<JSONObject>bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new DefaultObserver<JSONObject>(ForgotPassWordActivity.this) {
                    @Override
                    protected void onSuccess(JSONObject response) {
                        if (response != null) {
                            setQuestion(response);
                        }


                    }
                });

    }

    //重置密码接口
    private void resetPassWord() {

        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("password", password.getText().toString().trim());
        NetWorkManager.getInstance().getNetWorkApiService().forgotPassword(map, uid).compose(this.<JSONObject>bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new DefaultObserver<JSONObject>(ForgotPassWordActivity.this) {
                    @Override
                    protected void onSuccess(JSONObject response) {
                        if (response != null) {
                            jump(LoginActivity.class);
                            Intent intent = new Intent();
                            intent.setAction(constant.CLOSElOGIN_MYRECEIVER);
                            sendBroadcast(intent);
                            finish();

                            //   setQuestion(response);
                        }

                    }
                });


    }

    //验证
    private void verification() {
        Map<String, Object> map = new HashMap<>();
        map.put("secret_guard_id", questionId);
        map.put("account", account.getText().toString().trim());
        map.put("secret_guard_answer", secretInsuranceAnswer.getText().toString().trim());


        NetWorkManager.getInstance().getNetWorkApiService().verify(map).compose(this.<JSONObject>bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new DefaultObserver<JSONObject>(ForgotPassWordActivity.this) {
                    @Override
                    protected void onSuccess(JSONObject response) {
                        if (response != null) {
                            ForgotPassWordBean forgotPassWordBean = response.toJavaObject(ForgotPassWordBean.class);
                            token = forgotPassWordBean.getData().getToken();
                            uid = forgotPassWordBean.getData().getUid();
                            isVerify = true;
                            reset.setBackgroundResource(R.drawable.login_button_enable);
                            reset.setEnabled(true);
                            aa.setTextColor(Color.parseColor("#ff200404"));
                            bb.setTextColor(Color.parseColor("#ff200404"));
                            //编辑框重新获取焦点并弹出软键盘
                            rePassword.setFocusable(true);
                            rePassword.setFocusableInTouchMode(true);
                            rePassword.requestFocus();
                            //编辑框重新获取焦点并弹出软键盘
                            password.setFocusable(true);
                            password.setFocusableInTouchMode(true);
                            password.requestFocus();


                            success.setVisibility(View.VISIBLE);
                            verify.setVisibility(View.GONE);
                        }

                    }
                });
    }

    //密保问题列表数据
    private void setQuestion(JSONObject response) {
        RegisterQuestionBean registerQuestionBean = response.toJavaObject(RegisterQuestionBean.class);
        List<RegisterQuestionBean.DataBean> dataBeanList = registerQuestionBean.getData();
        if (0 == dataBeanList.size()) {
            secretInsuranceSpinner.setVisibility(View.GONE);
        } else {
            secretInsuranceSpinner.setVisibility(View.VISIBLE);
            questionId = dataBeanList.get(0).getId();
        }
        List<String> strings = new ArrayList<>();
        for (int i = 0; i < dataBeanList.size(); i++) {
            strings.add(dataBeanList.get(i).getQuestion());
        }

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, strings);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//绑定 Adapter到控件
        secretInsuranceSpinner.setAdapter(adapter);
        secretInsuranceSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                                       int pos, long id) {

                TextView textView = (TextView) view;
                textView.setTextColor(Color.parseColor("#737373"));
                textView.setTextSize(14f);
                for (int i = 0; i < dataBeanList.size(); i++) {
                    if (dataBeanList.get(i).getQuestion().equals(parent.getAdapter().getItem(pos))) {
                        questionId = dataBeanList.get(i).getId();
                    }

                }


            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // Another interface callback
            }
        });

    }

    @Override
    protected void extrasDoSome(Bundle extras) {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
